package com.hx.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TxAdvice {
    /**
     * 通知增强类
     */

    protected void begin(JoinPoint joinPoint){

        //可以通连接点获取相应的目标信息
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        List<Object> params=args == null ? null : Arrays.asList(args);
        System.out.println(methodName+"开启事务----参数"+params);
    }

    protected void commit(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        List<Object> params=args == null ? null : Arrays.asList(args);
        System.out.println(methodName+"提交事务----结果:"+result+"参数:"+params);
    }

    protected void rollback(Exception ex)  {
        System.out.println("回滚事务----"+ex.getMessage());
    }

    protected void release()  {
        System.out.println("释放资源----");
    }
    //环绕增强必须要有返回值
    public  Object around(ProceedingJoinPoint pjp){
        Object result=null;
        try {
            String methodName = pjp.getSignature().getName();
            Object[] args = pjp.getArgs();
            List<Object> params=args == null ? null : Arrays.asList(args);
            System.out.println(methodName+"开启事务----参数:"+params);
            //调用目标方法
            result =pjp.proceed();

            System.out.println(methodName+"提交事务----结果:"+result+"参数:"+params);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("回滚事务----"+throwable.getMessage());
        }finally {
            System.out.println("释放资源----");
        }
        return result;
    }

}
